How can you pass data between activities in Android?
How can you pass data between activities in Android?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
28-Jun-2023There are two ways to pass data between activities in Android:
putExtra()method to add the data to the intent. The data can be of any type, such as strings, integers, or objects. When the activity is started, the data will be passed to the activity'sonCreate()method.Here is an example of how to pass data using intents:
Code snippet
In this example, we are creating an intent to start the
SecondActivityclass. We are also adding a string with the key "name" and the value "John Doe" to the intent. When theSecondActivityis started, the data will be passed to the activity'sonCreate()method.Here is an example of how to pass data using shared preferences:
Code snippet
In this example, we are getting the data from the shared preferences file. The file is named "my_preferences" and it is stored in the private mode. The key of the data is "name" and the default value is an empty string.
Which method you use to pass data between activities will depend on your specific needs. If you need to pass a small amount of data, then using intents is a good option. If you need to pass a larger amount of data or if you need to persist the data across app sessions, then using shared preferences is a good option.